package repository

import (
	"trace-rule/internal/domain/model"

	"gorm.io/gorm"
)

type RuleRepository struct {
	db *gorm.DB
}

func NewRuleRepository(db *gorm.DB) *RuleRepository {
	return &RuleRepository{db: db}
}

func (r *RuleRepository) Create(rule *model.Rule) error {
	return r.db.Create(rule).Error
}

func (r *RuleRepository) Update(rule *model.Rule) error {
	return r.db.Save(rule).Error
}

func (r *RuleRepository) Delete(id uint) error {
	return r.db.Delete(&model.Rule{}, id).Error
}

func (r *RuleRepository) FindByID(id uint) (*model.Rule, error) {
	var rule model.Rule
	err := r.db.First(&rule, id).Error
	return &rule, err
}

func (r *RuleRepository) List(page, pageSize int) ([]model.Rule, int64, error) {
	var rules []model.Rule
	var total int64

	err := r.db.Model(&model.Rule{}).Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	err = r.db.Offset((page - 1) * pageSize).Limit(pageSize).Find(&rules).Error
	return rules, total, err
}

func (r *RuleRepository) ListEnabled() ([]model.Rule, error) {
	var rules []model.Rule
	err := r.db.Where("is_enabled = ?", true).Find(&rules).Error
	return rules, err
}
